package club.web51.classroom_tool.Controllers;

import club.web51.classroom_tool.DO.collDO.Academy;
import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Services.AcademyService;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 服务类
 * @author Hanyuhao
 * @since 1.0.0
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/academy")
@Api(value = "学院模块",tags={"学院操作接口"})

public class AcademyController {

    final
    AcademyService academyService;

    public AcademyController(AcademyService academyService) {
        this.academyService = academyService;
    }

    /**
     * 根据Academy的字段,自动生成条件,字段的值为null不生成条件
     * http://localhost:8080/user/?id=1
     * @param academy 实体对象
     * @param pageable 分页/排序对象
     * @return 返回的是实体,里面涵盖分页信息及状态码
     */
     @GetMapping
     @ApiOperation("动态查询，可输入对应对象的一个或多个属性")
     @RequiresPermissions(logical = Logical.OR, value = {"1","2", "3"})
     ResponseEntity<Object> search(Academy academy, Pageable pageable) {
             return academyService.search(academy, pageable);
     }
     @PostMapping
     @ApiOperation("创建学院")
     @RequiresPermissions(logical = Logical.AND, value = {"3"})
     Msg create(@RequestBody @Valid Academy academy, BindingResult bindingResult) {
         if(bindingResult.hasErrors()){
             throw new ErrDataException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
         }
         academy.setId(null);
         academyService.updateOne(academy);
         return MsgUtil.success();
     }
     @PutMapping
     @ApiOperation("修改学院")
     @RequiresPermissions(logical = Logical.AND, value = {"3"})
     Msg update(Academy academy){
         if(ObjectUtil.isNull(academy.getId()))
             throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY.getDescription());
         academyService.updateOne(academy);
         return MsgUtil.success();
     }
     @DeleteMapping("/")
     @ApiOperation("删除学院，输入ID")
     @RequiresPermissions(logical = Logical.AND, value = {"3"})
     Msg delete(Long id){
         academyService.deleteOne(id);
         return MsgUtil.success();
     }
}
